import Express from "express"
import multer from "multer"
import path from "path"
import fs from "fs/promises"
export const UploadRouter = Express.Router();

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.resolve(
            import.meta.dirname, '../static/upload'))
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1E9)
        const ext = path.extname(file.originalname);
        cb(null, file.fieldname + "-" + uniqueSuffix + ext);
    }
})

const upload = multer({
    storage: storage
})

UploadRouter.post("/", upload.single('file'), async (req, res) => {
    console.log(req.file);
    res.json({
        code: 0,
        msg: "上传成功",
        data: "http://localhost:8090/" + req.file.filename
    })
})

UploadRouter.delete("/",async(req,res)=>{
    const name =req.body.name;
    const filename =name.replace('http://localhost:8090','');
    await fs.unlink(path.resolve(import.meta.dirname,"../static/upload",filename))
    res.json({
        code:0,
        msg:"删除成功"
    })
})